﻿using AutoMapper;
using HuaweiCloud.Dotnet.Samples.Common;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Dtos;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Entities;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Specification;

namespace HuaweiCloud.Dotnet.Samples.ESports.Main.Manager
{
    public class DeviceManager : IDeviceManager
    {
        private readonly IRepository<BindInfo> _bindInfoRepository;
        private readonly IRepository<Device> _deviceRepository;
        private readonly IMapper _mapper;
        public DeviceManager(IRepository<BindInfo> bindInfoRepository
            , IRepository<Device> deviceRepository
            , IMapper mapper)
        {
            _bindInfoRepository = bindInfoRepository;
            _deviceRepository = deviceRepository;
            _mapper = mapper;
        }
        public async Task<List<DeviceDto>> GetDevicesByUserIdAsync(Guid userId, CancellationToken token = default)
        {
            var infos = await _bindInfoRepository.ListAsync(new BindInfoSpecification().GetByUserId(userId), token);
            if (infos.Count <= 0)
                return new List<DeviceDto>();
            else
            {
                var devices = await _deviceRepository.ListAsync(new DeviceSpecification(infos.Select(x => x.DeviceId)), token);
                return _mapper.Map<List<DeviceDto>>(devices);
            }
        }

        public async Task<Guid?> GetUserIdByDeviceIdAsync(Guid deviceId, CancellationToken token = default)
        {
            var info = await _bindInfoRepository.FirstOrDefaultAsync(new BindInfoSpecification(deviceId), token);
            return info?.UserId;
        }
    }
}
